//
//  AppDelegate.m
//  CarOfHome2
//
//  Created by dlios on 15/9/23.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "AppDelegate.h"
#import "HomeViewController.h"//首页
#import "Hot_rodViewController.h"//改装
#import "MusicViewController.h"//音乐
#import "SearchViewController.h"//品牌

#import "STYLeftViewController.h"

#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
//腾讯开放平台（对应QQ和QQ空间）SDK头文件
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>

//微信SDK头文件
#import "WXApi.h"
//新浪微博SDK头文件
#import "WeiboSDK.h"


@interface AppDelegate () <UIScrollViewDelegate,UITabBarControllerDelegate>

@property (nonatomic, strong) RESideMenu *sideMenuViewController;
@property (nonatomic,strong) UIScrollView *scrollView;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.rootViewController = [[UIViewController alloc]init];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
   
    
#pragma mark -  分享
    [ShareSDK registerApp:@"iosv1101"
          activePlatforms:@[
                            @(SSDKPlatformTypeSinaWeibo),
                            @(SSDKPlatformTypeTencentWeibo),
                            @(SSDKPlatformTypeWechat),
                            @(SSDKPlatformTypeQQ),
                            @(SSDKPlatformTypeDouBan)
                            ]
                 onImport:^(SSDKPlatformType platformType) {
                     
                     switch (platformType)
                     {
                         case SSDKPlatformTypeWechat:
                             [ShareSDKConnector connectWeChat:[WXApi class]];
                             break;
                         case SSDKPlatformTypeQQ:
                             [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                             break;
                         case SSDKPlatformTypeSinaWeibo:
                             [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                             break;
                             
                         default:
                             break;
                     }
                     
                 }
          onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo) {
              
              switch (platformType)
              {
                  case SSDKPlatformTypeSinaWeibo:
                      //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                      [appInfo SSDKSetupSinaWeiboByAppKey:@"a2194d4906da"
                                                appSecret:@"38a4f8204cc784f81f9f0daaf31e02e3"
                                              redirectUri:@"http://www.sharesdk.cn"
                                                 authType:SSDKAuthTypeBoth];
                      break;
                  case SSDKPlatformTypeTencentWeibo:
                      //设置腾讯微博应用信息，其中authType设置为只用Web形式授权
                      [appInfo SSDKSetupTencentWeiboByAppKey:@"801307650"
                                                   appSecret:@"ae36f4ee3946e1cbb98d6965b0b2ff5c"
                                                 redirectUri:@"http://www.sharesdk.cn"];
                      break;
                  case SSDKPlatformTypeWechat:
                      [appInfo SSDKSetupWeChatByAppId:@"wx4868b35061f87885"
                                            appSecret:@"64020361b8ec4c99936c0e3999a9f249"];
                      break;
                  case SSDKPlatformTypeQQ:
                      [appInfo SSDKSetupQQByAppId:@"100371282"
                                           appKey:@"aed9b0303e3ed1e27bae87c33761161d"
                                         authType:SSDKAuthTypeBoth];
                      break;
                  case SSDKPlatformTypeDouBan:
                      [appInfo SSDKSetupDouBanByApiKey:@"02e2cbe5ca06de5908a863b15e149b0b"
                                                secret:@"9f1e7b4f71304f2f"
                                           redirectUri:@"http://www.sharesdk.cn"];
                      break;
                      
                  default:
                      break;
              }
          }];
    /*读取夜间模式判断条件*/
    NSString *docP = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    NSString *readStrPath = [docP stringByAppendingPathComponent:@"isNight.txt"];
    NSString *contantStr = [NSString stringWithContentsOfFile:readStrPath encoding:NSUTF8StringEncoding error:nil];
    
    self.isNight = contantStr.intValue;

    NSUserDefaults * settings1 = [NSUserDefaults standardUserDefaults];
    NSString *key1 = [NSString stringWithFormat:@"is_first"];
    NSString *value = [settings1 objectForKey:key1];
    if (!value)  //如果没有数据
    {
        UIScrollView *uiScrollview = [[UIScrollView alloc] init];
        uiScrollview.frame = self.window.bounds;
        CGFloat width = self.window.frame.size.width;
        CGFloat height = self.window.frame.size.height;
        
        [self.window addSubview:uiScrollview];
        
        for (int i = 0; i <= 2; i++) {
            NSString *imageName = [NSString  stringWithFormat:@"yindao%d" ,i+1];
            UIImage *image = [UIImage imageNamed: imageName];
            UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
            imageView.frame = CGRectMake(i*width, 0, width, height);
            [uiScrollview addSubview:imageView];
        }
        self.scrollView = uiScrollview;
        uiScrollview.showsHorizontalScrollIndicator = NO;
        uiScrollview.contentSize = CGSizeMake(3*width, height);
        uiScrollview.pagingEnabled = YES;
        uiScrollview.backgroundColor = [UIColor grayColor];
        uiScrollview.delegate = self;
        
       
        //写入数据
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(165/ 375.0 * width, 590/ 667.0 *height , 50 / 375.0*width, 30 / 667.0 * height);
        [button setTitle:@"进入" forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:20];
        [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.window addSubview:button];
        NSUserDefaults * setting = [NSUserDefaults standardUserDefaults];
        NSString * key = [NSString stringWithFormat:@"is_first"];
        [setting setObject:[NSString stringWithFormat:@"false"] forKey:key];
        [setting synchronize];
    }
    else{

#pragma mark - 
    
    self.home = [[HomeViewController alloc] init];
    self.home.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"首页" image:[UIImage imageNamed:@"zhuye1"] selectedImage:[UIImage imageNamed:@"zhuye2"]];
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:self.home];
    
    self.Hot_rod = [[Hot_rodViewController alloc] init];
    self.Hot_rod.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"汽车改装" image:[UIImage imageNamed:@"GZ"] selectedImage:[UIImage imageNamed:@"GZ1"]];
    UINavigationController *rod = [[UINavigationController alloc] initWithRootViewController:self.Hot_rod];
    
    self.findCar = [[SearchViewController alloc] init];
    self.findCar.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"品牌大全" image:[UIImage imageNamed:@"PP"] selectedImage:[UIImage imageNamed:@"PP1"]];
    UINavigationController *search = [[UINavigationController alloc] initWithRootViewController:self.findCar];
    
    MusicViewController *music = [[MusicViewController alloc] init];
    music.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"汽车音乐" image:[UIImage imageNamed:@"music"] selectedImage:[UIImage imageNamed:@"music1"]];
    UINavigationController *autoShow = [[UINavigationController alloc] initWithRootViewController:music];
    
    self.tabBarController = [[UITabBarController alloc] init];
    
    self.tabBarController.viewControllers = @[navi, rod, search, autoShow];
    self.tabBarController.tabBar.barTintColor = [UIColor blackColor];
    self.tabBarController.tabBar.tintColor = [UIColor whiteColor];
    self.tabBarController.selectedIndex = 0;
    
    self.tabBarController.delegate = self;
    
    
    /* 抽屉 */
    STYLeftViewController *leftVC = [[STYLeftViewController alloc] init];

    
    self.sideMenuViewController = [[RESideMenu alloc] initWithContentViewController:self.tabBarController
                                                             leftMenuViewController:leftVC
                                                            rightMenuViewController:nil];
    
    
    self.sideMenuViewController.backgroundImage = [UIImage imageNamed:@"BJ"];
    self.sideMenuViewController.menuPreferredStatusBarStyle = 1; // UIStatusBarStyleLightContent
    self.sideMenuViewController.contentViewShadowColor = [UIColor blackColor];
    self.sideMenuViewController.contentViewShadowOffset = CGSizeMake(0, 0);
    self.sideMenuViewController.contentViewShadowOpacity = 0.6;
    self.sideMenuViewController.contentViewShadowRadius = 12;
    self.sideMenuViewController.contentViewShadowEnabled = YES;
    
    self.window.rootViewController = self.sideMenuViewController;
    }
    
    
    return YES;
}
- (void)buttonClicked : (UIButton *)button{
    
    self.scrollView.hidden = YES;
    button.hidden = YES;
    
    self.home = [[HomeViewController alloc] init];
    self.home.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"首页" image:[UIImage imageNamed:@"shouye.png"] tag:101];
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:self.home];
    
    self.Hot_rod = [[Hot_rodViewController alloc] init];
    self.Hot_rod.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"汽车改装" image:[UIImage imageNamed:@"GZ"] selectedImage:[UIImage imageNamed:@"GZ1"]];
    UINavigationController *rod = [[UINavigationController alloc] initWithRootViewController:self.Hot_rod];
    
    self.findCar = [[SearchViewController alloc] init];
    self.findCar.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"品牌大全" image:[UIImage imageNamed:@"PP"] selectedImage:[UIImage imageNamed:@"PP1"]];
    UINavigationController *search = [[UINavigationController alloc] initWithRootViewController:self.findCar];
    
    MusicViewController *music = [[MusicViewController alloc] init];
    music.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"汽车音乐" image:[UIImage imageNamed:@"music"] selectedImage:[UIImage imageNamed:@"music1"]];
    UINavigationController *autoShow = [[UINavigationController alloc] initWithRootViewController:music];
    
    self.tabBarController = [[UITabBarController alloc] init];
    
    self.tabBarController.viewControllers = @[navi, rod, search, autoShow];
    self.tabBarController.tabBar.barTintColor = [UIColor blackColor];
    self.tabBarController.tabBar.tintColor = [UIColor whiteColor];
    self.tabBarController.selectedIndex = 0;
    
    self.tabBarController.delegate = self;
    
    
    /* 抽屉 */
    STYLeftViewController *leftVC = [[STYLeftViewController alloc] init];
    
    
    self.sideMenuViewController = [[RESideMenu alloc] initWithContentViewController:self.tabBarController
                                                             leftMenuViewController:leftVC
                                                            rightMenuViewController:nil];
    
    
    self.sideMenuViewController.backgroundImage = [UIImage imageNamed:@"BJ"];
    self.sideMenuViewController.menuPreferredStatusBarStyle = 1; // UIStatusBarStyleLightContent
    self.sideMenuViewController.contentViewShadowColor = [UIColor blackColor];
    self.sideMenuViewController.contentViewShadowOffset = CGSizeMake(0, 0);
    self.sideMenuViewController.contentViewShadowOpacity = 0.6;
    self.sideMenuViewController.contentViewShadowRadius = 12;
    self.sideMenuViewController.contentViewShadowEnabled = YES;
    
    self.window.rootViewController = self.sideMenuViewController;
    
    
}
//- (void) onPointClick
//{
//    NSLog(@"onPointClick");
//    
//    CGFloat offsetX = self.page.currentPage * self.scrollView.frame.size.width;
//    [UIView animateWithDuration:0.3 animations:^{
//        self.scrollView.contentOffset = CGPointMake(offsetX, 0);
//    }];
//    
//}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.lanou3g.CarOfHome2" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CarOfHome2" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CarOfHome2.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

@end
